/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月24日
 */
package com.massyframework.beanskin.runtime.nativelib.script;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.service.ServiceReference;
import com.massyframework.beanskin.service.script.ScriptEngineNotFoundException;
import com.massyframework.beanskin.service.script.ScriptFile;
import com.massyframework.beanskin.util.IOUtils;
import com.massyframework.beanskin.util.version.VersionRange;

/**
 * 缺省的脚本引擎构建器
 * @author huangkh
 *
 */
final class DefaultScriptEngineBuilder extends AbstractScriptEngineBuilder {
	
	/**
	 * 构造方法
	 * @param module {@link Module}
	 */
	public DefaultScriptEngineBuilder(Module<?> module) {
		super(module);
	}

	@Override
	protected ScriptEngine doBuild() throws ScriptEngineNotFoundException, ScriptException, IOException{
		ScriptEngine result = this.createScriptEngine();
		this.injectScriptObjects(result, this.getObjectMap());
		
		//加载指定的脚本文件
		this.loadScrptFiles(result, this.getScriptFiles());
		return result;
	}
	
	/**
	 * 加载脚本文件
	 * @param engine {@link ScriptEngine},脚本引擎
	 * @param list {@link List},脚本文件路径
	 */
	protected void loadScrptFiles(ScriptEngine engine,List<ScriptFile> list) throws IOException ,ScriptException{
		if (list.isEmpty()) return;
		
		for (ScriptFile file: list) {
					
			if (file.isEncrypt()) {
				this.loadEncryptedScriptFile(engine, file);
			}else {
				this.loadScriptFile(engine, file.getURL());
			}
		}
	}
	
	/**
	 * 加载脚本文件
	 * @param engine {@link ScriptEngine},脚本引擎
	 * @param url {@link URL},脚本文件路径
	 */
	protected Object loadScriptFile(ScriptEngine engine, URL url) throws IOException ,ScriptException{
		InputStream is = null;
		Reader reader = null;
		try {
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			
			is = conn.getInputStream();
			reader = new InputStreamReader(is);
			return engine.eval(reader);
		}finally {
			IOUtils.close(reader);
			IOUtils.close(is);
		}
	}
	
	/**
	 * 加载加密的脚本文件
	 * @param engine {@link ScriptEngine},脚本引擎
	 * @param file  {@link String},模块标识符
	 * @throws IOException 读取加密脚本时发生的io例外
	 * @throws ScriptException 加载脚本发生的例外 
	 */
	protected Object loadEncryptedScriptFile(ScriptEngine engine, ScriptFile file) throws IOException , ScriptException {
		byte[] data = this.toByteArray(file.getURL());		
		String moduleIdentifier = file.getModule().toIdentifier();
		return this.loadEncryptedScriptFile(engine, moduleIdentifier, data);
	}
	
	/**
	 * 加载加密的脚本文件
	 * @param engine {@link ScriptEngine},脚本引擎
	 * @param moduleIdentifier {@link String},模块标识符
	 * @param data {@link byte[]}，密文
	 * @return {@link Object}
	 */
	protected native Object loadEncryptedScriptFile(ScriptEngine engine, String moduleIdentifier, byte[] data);
	
	/**
	 * 从{@code url}加载字节数组
	 * @param url {@link URL}, 脚本url地址
	 * @return {@link byte[]}
	 * @throws IOException
	 */
	protected byte[] toByteArray(URL url) throws IOException {
		InputStream is = null;
		try {
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			is = conn.getInputStream();
			
		    ByteArrayOutputStream output = new ByteArrayOutputStream();
		    byte[] buffer = new byte[4096];
		    int n = 0;
		    while (-1 != (n = is.read(buffer))) {
		        output.write(buffer, 0, n);
		    }
		    return output.toByteArray();
		}finally {
			IOUtils.close(is);
		}
	}
		
	/**
	 * 注入脚本对象
	 * @param engine {@link ScriptEngine},脚本引擎
	 * @param objectMap {@link Map},对象服务
	 */
	protected void injectScriptObjects(ScriptEngine engine, Map<String, Object> objectMap) {
		Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
		for (Map.Entry<String, Object> entry: objectMap.entrySet()) {
			bindings.put(entry.getKey(), entry.getValue());
		}
	}
	
	/**
	 * 创建脚本引擎
	 * @return {@link ScriptEngine}
	 * @throws ScriptEngineNotFoundException
	 */
	protected ScriptEngine createScriptEngine() throws ScriptEngineNotFoundException{
		Module<?> module = this.getModule();
		VersionRange range = VersionRange.EMPTY;
		if (module instanceof Assembly) {
			range = ((Assembly)module).getConfig().getVersionRangeWithBeanContext();
		}
				
		ServiceReference<ScriptEngine> found = null;
		List<ServiceReference<ScriptEngine>> references =
				this.getServiceRepository().getServiceReferences(ScriptEngine.class);
		for (ServiceReference<ScriptEngine> reference: references) {
			if (range.includes(reference.getServiceVersion())) {
				found = reference;
				break;
			}
		}
		if (found == null) throw new ScriptEngineNotFoundException(range);
		ScriptEngine result = this.getServiceRepository().getService(found).orElse(null);
		if (result == null) {
			throw new ScriptEngineNotFoundException(range);
		}
		return result;
	}

}
